#!/usr/bin/env twistd -noy
"""
Because the shebang has the command you need to run this script, all you need
to do is ensure that:
 * you have Twisted installed, and
 * this script is executable

After running it, you can visit this URL:
  http://localhost/data/
where you will see a list of links. Clickig each one will take you to a simple
report on the usage of the given system or python resource.
"""

from twisted.application import internet, service
from twisted.web import static, server
from twisted.web.resource import Resource

import resources

class Data(Resource):

    def getChild(self, path, request):
        if path == 'pid':
            data = resources.getPID()
        elif path == 'msgs':
            sent = resources.getRUsageSelf().msgsSent
            rec = resources.getRUsageSelf().msgsReceived
            data = (sent, rec)
        elif path == 'reclaims':
            data = resources.getRUsageSelf().pageReclaims
        elif path == 'swap':
            data = resources.getRUsageSelf().swaps
        elif path == 'switches':
            vol = resources.getRUsageSelf().volCtxSwitches
            invol = resources.getRUsageSelf().involCtxSwitches
            data = (vol, invol)
        elif path == 'times':
            user = resources.getTimes().user.asSeconds
            system = resources.getTimes().system.asSeconds
            data = (user, system)
        elif path == 'ressize':
            data = str(resources.getStat().resSize.mb) + ' MB'
        elif path == 'virtsize':
            data = str(resources.getStat().virtSize.mb) + ' MB'
        else:
            data = None
        self.rdata = {'key': path, 'val': data}
        return self

    def render_GET(self, request):
        if hasattr(self, 'rdata'):
            payload = "<html><pre>%(key)s: %(val)s</pre>" % self.rdata
        else:
            payload = (
            '<html><ul>' +
            '<li><a href="/data/pid">pid</a></li>' +
            '<li><a href="/data/msgs">msgs</a></li>' +
            '<li><a href="/data/reclaims">reclaims</a></li>' +
            '<li><a href="/data/swap">swap</a></li>' +
            '<li><a href="/data/switches">switches</a></li>' +
            '<li><a href="/data/times">times</a></li>' +
            '<li><a href="/data/ressize">ressize</a></li>' +
            '<li><a href="/data/virtsize">virtsize</a></li>' +
            '</ul><html>')
        return payload

# resources
root = static.File("/Users/oubiwann/Sites")
root.putChild('data', Data())

application = service.Application('web')
site = server.Site(root)
sc = service.IServiceCollection(application)
i = internet.TCPServer(6969, site)
i.setServiceParent(sc)
